﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WcfServer.Classes.Server;
using WcfServer.Classes.Utility;

namespace Client.View
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Page
    {
        public Login()
        {
            InitializeComponent();
        }

        private void LoginAction(object sender, RoutedEventArgs e)
        {
            var connection = new Client.ServerService.ServerServiceClient();

            //get a free port to listen on!
            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Any,0);
            listener.Bind(ipe);

            LoginData ld = new LoginData()
            {
                UserID = UN.Text,
                UserIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString(),
                Password = EncryptionHandler.HashSHA256(Encoding.UTF8.GetBytes(PW.Password)),
                Timestamp = DateTime.Now,
                listeningPort = (listener.LocalEndPoint as IPEndPoint).Port,
                UserSessionKey = KeyHandler.generateAESKey()
            };

            FileStream fs = new FileStream("server_public.xml", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            String xml = sr.ReadToEnd();

            byte[] response = connection.AuthenticateUser(ld.SendUsingServerPublic(xml));

            LoginResponse lr = new LoginResponse(response, ld.UserSessionKey);
            //TODO:Validate sign.
            //lr.Sign;
            foreach (var i in lr.Friends)
            {
                KeyHandler.savePublicXML(i.UserID, i.publicKey);
            }
            MainWindow.ClientServerSessionKey = ld.UserSessionKey;
            MainWindow.CurrentUserName = ld.UserID;
            this.NavigationService.Navigate(new FriendList(lr.Friends,listener));
        }

        private void GoBack(object sender, RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
                this.NavigationService.GoBack();
        }
    }
}
